/**
 * Copyright (C) 2016 inote.online
 * FileName:	AuthorizationRequestFilter.java
 * Created:		2016年12月4日 下午7:47:11
 */

package sui.jersey.filter;

import java.io.IOException;
import java.nio.charset.Charset;
import java.security.Principal;

import javax.annotation.Priority;
import javax.ws.rs.Priorities;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.ext.Provider;

import org.apache.commons.lang3.StringUtils;
import org.glassfish.jersey.internal.util.Base64;
import org.slf4j.Logger;

import sui.utils.logs.LogUtils;

/**
 * <p>
 * Description: 
 * </p>
 * @author 	XQF SUI
 * @Created 2016年12月4日 下午7:47:11
 * @version 1.0
 */
@Provider  
@Priority(Priorities.AUTHENTICATION)
public class AuthorizationRequestFilter implements ContainerRequestFilter {

	Logger logger = LogUtils.get();
	
	private static final String USERNAME = "admin";
	private static final String PASSWORD = "admin";
	
	@Override
	public void filter(ContainerRequestContext requestContext) throws IOException {
		
		logger.debug("开始认证...");
		
		String authHeader = requestContext.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
		
		if (StringUtils.isNotBlank(authHeader) && authHeader.startsWith("Basic")) {
			
			String[] userInfo = StringUtils
					.toEncodedString(Base64.decode(authHeader.substring(6).getBytes()), Charset.forName("utf-8"))
					.split(":");
			
			logger.debug("认证账户信息[{}][{}]", userInfo[0], userInfo[1]);
			
			// 根据验证账号密码
			if (USERNAME.equals(userInfo[0]) && PASSWORD.equals(userInfo[1])) {
				
				logger.debug("认证通过.");
				
				requestContext.setSecurityContext(new SecurityContext() {
					
					@Override
					public boolean isUserInRole(String role) {
						return true;
					}
					
					@Override
					public boolean isSecure() {
						return false;
					}
					
					@Override
					public Principal getUserPrincipal() {
						return new Principal() {
							
							@Override
							public String getName() {
								return USERNAME;
							}
						};
					}
					
					@Override
					public String getAuthenticationScheme() {
						return "BASIC";
					}
				});
				
				return;
			}
		}
		
		logger.debug("认证失败, 账号密码不正确!");
		
		requestContext.abortWith(
				Response.status(Response.Status.UNAUTHORIZED).header(HttpHeaders.WWW_AUTHENTICATE, "Basic").build());
	}

}
